/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(28/02/25)
 *         Author:  LingYun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "28/02/25 19:39:52"
 *                 
********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>

int get_tempreature(float *temp);     //功能函数写在主函数前

int main(int argc, char *argv[])
{
	float    temp;
	int      rv;        

	rv = get_tempreature(&temp);    //rv为功能函数返回值
	if (rv< 0)                      //功能函数代码段出现错误，打印错误原因
	{
		printf("get tempreature failure, return value: %d\n", rv);
		return -1;
	}

	printf("temp: %f\n", temp);
}


int get_tempreature(float *temp)     //*temp传回temp的地址
{
	int              fd = -1;
	char             buf[128];
	char            *ptr = NULL;
	DIR             *dirp = NULL;
	struct dirent   *direntp = NULL;
	char             w1_path[64]="/sys/bus/w1/devices/";
	char             chip_sn[32];
	int              found = 0;

	dirp=opendir(w1_path);           //打开文件
	if(!dirp)
	{
		printf("open folder %s failure: %s\n", w1_path,  strerror(errno));
		return -1;
	}

	while(NULL != (direntp=readdir(dirp)))    //在文件中查找"28-"，并将其存入chip_sn
	{
		if(strstr(direntp->d_name,"28-"))
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
			found = 1;                        //表示成功找到·
		}
	}

	closedir(dirp);

	if(!found)                            //没找到"28-"，打印失败原因
	{
		printf("Can not find ds18b20 chipset\n");
		return -2;
	}

	strncat(w1_path, chip_sn,sizeof(w1_path)-strlen(w1_path));  //把chip_sn追加到w1_path后
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));   //把"/w1_slave"追加到w1_path后

	if((fd=open(w1_path, O_RDONLY)) < 0)    //打开路径w1_path的文件失败，打印错误原因
	{
		printf("open file failure: %s\n", strerror(errno));  
		perror("open file failure");
		return -3;
	}	

	memset(buf, 0, sizeof(buf));               //初始化buf，消除随机值
	if(read(fd, buf, sizeof(buf)) < 0)         //将文件中的内容存入buf
	{
		printf("read data from fd=%d failure: %s\n",fd, strerror(errno));
		return -4;
	}
	
	ptr=strstr(buf,"t=");           //在buf中找到“t=”，并将地址存入ptr
	if(!ptr)                        //当ptr为0，找不到
	{
		printf("Can not find t= string\n");
		return -5;
	}
	
	ptr += 2;
	
	*temp = atof(ptr)/1000;        //字符串转为浮点数
	printf("tempreature: %f\n", *temp);

	close(fd);                      //关闭文件

	return 0;
}
